package jp.co.menox.controller.tmserver.gate;

import jp.co.menox.controller.tmserver.TmServerControllerBase;
import jp.co.menox.tmcommon.model.User;
import jp.co.menox.tmserver.service.UserService;

import org.slim3.controller.Navigation;
import org.slim3.controller.validator.Validators;

/**
 * ログイン処理
 * @author
 *
 */
public class RequestLoginController extends TmServerControllerBase {

    @Override
    protected Navigation setUp() {
        // 基底クラスの処理を無効化
        return null;
    }

    @Override
    public Navigation run() throws Exception {
        if (!isPost() || !isValid()) {
            return forward("login");
        }
        
        String loginId = this.<String>requestScope("userId");
        String password = this.<String>requestScope("userPass");
        User model = userService.getUserModel(loginId, password);
        if (model == null) {
            // 認証不可
            requestScope("loginMessage", "IDまたはパスワードが異なります。");
            return forward("login.jsp");
        }
        
        // 認証ＯＫ

        // セッション開始
        sessionScope("UserId", model.getId());

        // channel用設定
        setChannel();

        requestScope("userName", model.getName());
        
        return forward("menu.jsp");
    }

    private boolean isValid() {
        Validators v = new Validators(request);
        v.add("userId", v.required(), v.minlength(4), v.maxlength(64));
        v.add("userPass", v.required(), v.minlength(4), v.maxlength(512));
        return v.validate();
    }
}
